package com.pushtalk.utils;


import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import org.apache.commons.codec.binary.Base64;


public class KkSSO {
	
	/* 
	*LtpaToken的结构是 urlencode（Header码 + 验证码） 
	*Header码是： 4位占位符 + 8位16进制创建时间 + 8位16进制过期时间 + username 
	*验证码：ASCII数组运算(sha1加密(Header码 + base64解码(秘钥))) 
	*	$headerCode = chr(0).chr(1).chr(2).chr(3);
	*	$header = strtoupper($headerCode.dechex($ctime).dechex($etime)).$username;
	*   return base64_encode($header.self::stringToByte(sha1($header.base64_decode($secret))));
	*/
	public static String KkTokenGen(String username,long createTime,long expTime,String secret,String charset) throws UnsupportedEncodingException{

		String LtpaToken="";		
		//4位占位符
		String headerCode = String.valueOf(ascii2Char(0)) 
				+ String.valueOf(ascii2Char(1))
				+ String.valueOf(ascii2Char(2))
				+ String.valueOf(ascii2Char(3))	;	
		//JAVA时间戳长度是13位，PHP时间戳长度是10位，输入时要注意
		String dateNowHex = Long.toHexString(createTime);
		String dateExpHex = Long.toHexString(expTime);	
		//组装header头码
		String header = (headerCode + dateNowHex + dateExpHex).toUpperCase() + username;
		
		try {
			String resultSha1 = SHA1(header + new String(Base64.decodeBase64(secret),charset));
			//ACSII转换
			String stringToByte2STR = stringToByte2(resultSha1);
			String resultBase64Encode = new String(Base64.encodeBase64((header+stringToByte2STR).getBytes(charset) ));
			//URL_encode转换
			String resultURLEncoder =  java.net.URLEncoder.encode(resultBase64Encode,charset);
			return resultURLEncoder;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}					
		return LtpaToken;
	}
	
	/* 
	* KKToken生成，，7天过期，因为信息存在当天没看到或没点击的情况
	*/
	public static String KkTokenGen(String username) throws UnsupportedEncodingException{

		String LtpaToken="";		
		//4位占位符
		String headerCode = String.valueOf(ascii2Char(0)) 
				+ String.valueOf(ascii2Char(1))
				+ String.valueOf(ascii2Char(2))
				+ String.valueOf(ascii2Char(3))	;	
		//JAVA时间戳长度是13位，PHP时间戳长度是10位，输入时要注意
		String javaTime = String.valueOf(new Date().getTime());
		long phpTime = Long.parseLong(javaTime.substring(0, 10));
		String dateNowHex = Long.toHexString(phpTime);
		String dateExpHex = Long.toHexString(phpTime + 604800);
		//组装header头码
		String header = (headerCode + dateNowHex + dateExpHex).toUpperCase() + username;
		
		try {
			String resultSha1 = SHA1(header + new String(Base64.decodeBase64(KkConfig.SecretKey),KkConfig.Charset));
			//ACSII转换
			String stringToByte2STR = stringToByte2(resultSha1);
			String resultBase64Encode = new String(Base64.encodeBase64((header+stringToByte2STR).getBytes(KkConfig.Charset) ));
			//URL_encode转换
			String resultURLEncoder =  java.net.URLEncoder.encode(resultBase64Encode,KkConfig.Charset);
			return resultURLEncoder;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}					
		return LtpaToken;
	}
		
	public static String stringToByte2(String str){
		int len = str.length()/2;
		String[] arrStr = new String[len];
		StringBuffer sb =  new StringBuffer();
		
		for (int i=0;i<len;i++)
		{
			arrStr[i] = str.substring(i*2,i*2 + 2);
			sb.append(String.valueOf(ascii2Char(Integer.valueOf(Integer.parseInt(arrStr[i],16)))));
		}		
		return sb.toString();
	}
	
	public static String SHA1(String str){
        String sha1 = "";
        try{
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.reset();
            md.update(stringToByte(str));

            sha1 = byteToHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sha1;
    }

    private static String byteToHex(byte[] b)
    {
		StringBuffer sb =  new StringBuffer();

        for (int i=0; i < b.length; i++) {
        	sb.append(Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 ));
        }
        return sb.toString();
    }

    public static byte[] stringToByte(String str){
        return str.getBytes(StandardCharsets.ISO_8859_1); 
    }

//    public static String stringToByteString(String str){
//        String result = "";
//        int len = 2;
//        int end = len;
//        String s;
//        for (int i = 0; i < str.length();) {
//            if (end > str.length()){
//                end = str.length();
//            }
//
//            s = str.substring(i, end);
//            i = end;
//            end = i + len;
//
//            int tmp = Integer.valueOf(s, 16);
//
//            result += Character.toString((char) tmp);
//        }
//        return result;
//    }

//    public static String encodeSso(String username, int ctime, int etime, String secret) {
//        String result = "";
//        String headerCode = Character.toString((char) 0)
//                + Character.toString((char) 1)
//                + Character.toString((char) 2)
//                + Character.toString((char) 3);
//
//        String header = (headerCode + Integer.toHexString(ctime) + Integer.toHexString(etime)).toUpperCase() + username;
//
//        BASE64Decoder decode = new BASE64Decoder();
//        BASE64Encoder encode = new BASE64Encoder();
//
//        try{
//            byte[] decodedBytes = decode.decodeBuffer(secret);
//            String tmp = SHA1(header + new String(decodedBytes, "ISO_8859_1"));
//
//            result = encode.encode(stringToByte(header + stringToByteString(tmp)));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        return result;
//    }
	
	 static char ascii2Char(int ASCII) {  
	        return (char) ASCII;  
	 } 

}
